/* -----------------------------------------------------------------------------
 * PROJECT    : lwf_common
 * FILE       : FileReader.java
 *
 * HISTORY:
 * Date          Author                        Description
 * ----------------------------------------------------------------------------- 
 * Dec 9, 2010  mycodetalks			       Created
 */
package net.lwf.file.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import net.lwf.exception.ExceptionUtil;


/**
 * Class description goes here
 */
public class FileReader {
	
    public static byte[] loadFile(String sourcePath) {
    	byte[] output = null;
    	InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(sourcePath);
			output = readFully(inputStream);
			if (inputStream != null) {
				inputStream.close();
			}
		} 
		catch(IOException ioex) {
			ExceptionUtil.logAndThrowException(FileReader.class, ioex);
		}		

		return output;
	}

	public static byte[] readFully(InputStream stream) {
		byte[] output = null;
		if(stream != null) {
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

			int data;
			try {
				while ((data = stream.read()) >= 0) {
					outputStream.write(data);
				}
				output = outputStream.toByteArray();
				stream.close();
			}
			catch(IOException ioex) {
				ExceptionUtil.logAndThrowException(FileReader.class, ioex);
			}

		}
		else {
			//TODO throw net.lwf.exception
		}

		return output;
	}

	public static byte[] convertDocToByteArray(String sourcePath) {
		byte[] byteArray = null;
		
		if(sourcePath != null) {
			try {
				InputStream inputStream = new FileInputStream(sourcePath);

				String inputStreamToString = inputStream.toString();
				byteArray = inputStreamToString.getBytes();

				inputStream.close();
			} catch (FileNotFoundException fnfex) {
				ExceptionUtil.logAndThrowException(FileReader.class, fnfex);
			} catch (IOException ioex) {
				ExceptionUtil.logAndThrowException(FileReader.class, ioex);
			}
		}
		

		return byteArray;
	}
	
	/*

	public static void convertByteArrayToDoc(byte[] b) {

		OutputStream out;
		try {
			out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
			out.close();
			System.out.println("write success");
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	*/






} //FileReader



